package cn.vawn.exam.controller;

import cn.vawn.base.consts.AppConsts;
import cn.vawn.base.controller.BaseController;
import cn.vawn.base.dto.PageDTO;
import cn.vawn.base.dto.ResponseResult;
import cn.vawn.base.util.DateUtil;
import cn.vawn.base.util.StringArrayUtil;
import cn.vawn.exam.entity.Answer;
import cn.vawn.exam.entity.Questions;
import cn.vawn.exam.entity.QuestionsType;
import cn.vawn.exam.service.IAnswerService;
import cn.vawn.exam.service.IQuestionTypeService;
import cn.vawn.exam.service.IQuestionsService;
import cn.vawn.exam.service.exception.DataNotFoundException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("exam")
public class QuestionsController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(QuestionsController.class);

    @Resource
    private IQuestionsService questionsService;

    @Resource
    private IAnswerService answerService;

    @Resource
    private IQuestionTypeService questionTypeService;

    @RequestMapping(value = "/getAllQuestion", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<PageDTO> getAllQuestions(HttpServletRequest request, HttpServletResponse response) {
        //token验证
//        System.out.println(request.getParameter("token"));
//        System.out.println(request.getParameter("pageNumber"));
//        System.out.println(request.getParameter("pageSize"));

        ResponseResult<PageDTO> rr = null;

//        List<Map<String, Object>> questions = questionsService.getAllQuestions();

        PageDTO questionList = questionsService.serachQuestions(getPage());

        rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, questionList);

        return rr;
    }

    @RequestMapping(value = "/getPartQuestion", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<PageDTO> getQuestionsPart(HttpServletRequest request, HttpServletResponse response) {
        //token验证

        ResponseResult<PageDTO> rr = null;
        String type = request.getParameter("type");
//        System.out.println(type);
        String content = request.getParameter("content");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");

        logger.info("try to get question by parameter : type = " + type + ", content = " +
                    content + ",startTime = " + startTime + ",endTime = " +  endTime);

        PageDTO questions = questionsService.getPartQuestions(getPage(),content, type, startTime, endTime);

        rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, questions);

        return rr;
    }

    @RequestMapping(value = "/compileQuestion", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Void> compileQuestion(@RequestBody String data) {
//        System.out.println(data);
        JSONObject object = JSONObject.fromObject(data);

//        String token = object.getString("token");
//        System.out.println(token);

        String questionsId = object.getString("questionsId");
//        System.out.println("questionsId");

        logger.info("copmpile question by parameter : questionId = " + questionsId);

        Questions questions = questionsService.getAnswers(Integer.parseInt(questionsId));
        String answerIds = "";
        if (questions != null){
            answerIds = questions.getAnswerIds();
        }
        answerService.batchDelete(StringArrayUtil.stringArrToList(answerIds.split(",")));

        JSONArray array = object.getJSONArray("answers");
        List<Answer> list = new ArrayList<>();

        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = (JSONObject) array.get(i);
            if(obj != null){
                Answer answer = new Answer();

                answer.setContent(obj.getString("content"));
                answer.setLocalUnitermIds(obj.getString("localUnitermIds"));
                answer.setCreatedTime(new Date());

                list.add(answer);
            }

        }

        answerIds = answerService.addAnswersBatch(list);

        String content = object.getString("content");
        String classType = object.getString("classType");
        int optionType = object.getInt("optionType");

        questions.setAnswerIds(answerIds);
        questions.setClassType(classType);
        questions.setContent(content);
        questions.setOptionType(optionType);
        questions.setCreatedTime(new Date());

        questionsService.updateQuestion(questions);

//        questionsService.addQuestion(content, classType, optionType, answerIds);

        return new ResponseResult<Void>(1, "问题添加成功");
        //
//        String answerIds = answerService.addAnswersBatch(list);
//
//        ResponseResult<Void> rr = null;
//
//        try {
//            questionsService.updateQuestion(question);
//            rr = new ResponseResult<Void>(1, "问题更新成功");
//        } catch (DataNotFoundException e) {
//            rr = new ResponseResult<Void>(0, e.getMessage());
//        }
//
//        return rr;
    }

    @RequestMapping(value = "/dltQuestion", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Void> dltQuestion(HttpServletRequest request) {
        //token验证
//        String token = request.getParameter("token");
//        System.out.println(token);

        String questionsId = request.getParameter("questionId");
        logger.info("delete question by parameter : questionId = " + questionsId);
//        System.out.println(questionsId);

        ResponseResult<Void> rr = null;
        try {
            boolean contains = questionsService.checkQuestionId(Integer.parseInt(questionsId));
            if(contains) {
                rr = new ResponseResult<>(0, "请先将题目与问卷解绑，再做操作");
            } else {
                questionsService.deleteQuestion(Integer.parseInt(questionsId));
                rr = new ResponseResult<Void>(1, "删除成功");
            }
        } catch (DataNotFoundException e) {
            rr = new ResponseResult<Void>(0, e.getMessage());
        }

        return rr;
    }

    @RequestMapping(value = "/addQuestion", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Void> addQuestion(@RequestBody String data) {
//        System.out.println(data);
        JSONObject object = JSONObject.fromObject(data);

//		String token = object.getString("token");
//        System.out.println(token);
        //
        JSONArray array = object.getJSONArray("answers");
        logger.info("add question by parameter : answers = " + array);
        List<Answer> list = new ArrayList<>();
        //
        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = (JSONObject) array.get(i);

            Answer answer = new Answer();

            answer.setContent(obj.getString("content"));
//            answer.setSerial(obj.getString("option"));
            answer.setLocalUnitermIds(obj.getString("localUnitermIds"));
            answer.setCreatedTime(new Date());

            list.add(answer);
        }
        //
        String answerIds = answerService.addAnswersBatch(list);

        String content = object.getString("content");
        String classType = object.getString("classType");
        int optionType = object.getInt("optionType");

        questionsService.addQuestion(content, classType, optionType, answerIds);

        return new ResponseResult<Void>(1, "问题添加成功");
    }

    @RequestMapping(value = "/getAllClassType", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<List<QuestionsType>> getAllClassType(String token) {
        //token验证

        ResponseResult<List<QuestionsType>> rr =
                new ResponseResult<>(1, questionTypeService.getAllType());
        return rr;
    }

    @RequestMapping(value = "/getQuestion", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<Map<String, Object>> getQuestion(HttpServletRequest request) {
        //token验证
//        String token = request.getParameter("token");
//        System.out.println("get question by id : token" + token);

        String questionsId = request.getParameter("questionsId");
        logger.info("get question by questionId = " + questionsId);

        Map<String, Object> result = questionsService.getQuestions(Integer.parseInt(questionsId));

        ResponseResult<Map<String, Object>>  rr =
                new ResponseResult<>(1,result);
        return rr;
    }

    @RequestMapping(value = "/getAllTypeName", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<PageDTO> getAllTypeName(@RequestParam(value = "typeName", required = false) String typeName,
                                                  @RequestParam(value = "startTime", required = false) String startTime,
                                                  @RequestParam(value = "endTime", required = false) String endTime) {

        logger.info("try to search paper type by typeName: " + typeName + ", startTime: " + startTime + ", endTime: " + endTime);
        Date startDate = null;
        if (!"".equals(startTime)) {
            startDate = DateUtil.parseDate(startTime);
        }
        Date endDate = null;
        if (!"".equals(endTime)) {
            endDate = DateUtil.parseDate(endTime);
        }
        PageDTO paperTypeList = questionTypeService.searchQuestionType(getPage(), typeName, startDate, endDate);
        ResponseResult<PageDTO> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, paperTypeList);
        return rr;
    }

    @RequestMapping(value = "/createQuestionType", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Integer> createQuestionType(@RequestBody QuestionsType questionsType) {
        logger.info("try to create paper type by QuestionsType: " + questionsType);
        questionsType.setId(null);
        questionsType.setStatus(0);
        questionsType.setIsDeleted(false);
        questionsType.setCreatedBy(getCurrentUser().getId());
        questionsType.setCreatedTime(new Date());
        questionTypeService.insert(questionsType);
        ResponseResult<Integer> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, 1);
        return rr;
    }

    @RequestMapping(value = "/getQuestionTypeById", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<QuestionsType> getQuestionTypeById(Integer questionTypeId) {
        logger.info("try to get question type by questionTypeId: " + questionTypeId);

        QuestionsType questionsType = questionTypeService.selectById(questionTypeId);
        ResponseResult<QuestionsType> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, questionsType);
        return rr;
    }

    @RequestMapping(value = "/updateQuestionType", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Integer> updateQuestionType(@RequestBody QuestionsType questionsType) {
        logger.info("try to update question type by questionTypeId: " + questionsType.getId() + ", typeName: " + questionsType.getTypeName());

        questionsType.setUpdatedBy(getCurrentUser().getId());
        questionsType.setUpdatedTime(new Date());

        questionTypeService.update(questionsType);

        ResponseResult<Integer> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, 1);
        return rr;
    }

    @RequestMapping(value = "/dltQuestionTypeById", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<Integer> dltQuestionTypeById(Integer questionTypeId) {
        logger.info("try to delete paper type by questionTypeId: " + questionTypeId);
        QuestionsType questionsType = new QuestionsType();
        questionsType.setId(questionTypeId);
        questionsType.setUpdatedBy(getCurrentUser().getId());
        questionsType.setUpdatedTime(new Date());

        questionTypeService.delete(questionsType);

        ResponseResult<Integer> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, 1);
        return rr;
    }

}
